package com.cjp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjp.mapper.ArticleMapper;
import com.cjp.pojo.Article;
import com.cjp.pojo.PageBean;
import com.cjp.pojo.dto.ArticleAddDTO;
import com.cjp.pojo.dto.ArticleUpdateDTO;
import com.cjp.pojo.vo.ArticleVO;
import com.cjp.service.IArticleService;
import com.cjp.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>  implements IArticleService {

    private final ArticleMapper articleMapper;

    @Override
    public void addArticle(ArticleAddDTO articleAddDTO) {
        Article article = BeanUtil.copyProperties(articleAddDTO, Article.class);

        Map<String, Object> claims = ThreadLocalUtil.get();
        article.setCreateUser(Long.valueOf(claims.get("id").toString()));
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.insert(article);
    }

    @Override
    public void updateArticle(ArticleUpdateDTO articleUpdateDTO) {
        Article article = BeanUtil.copyProperties(articleUpdateDTO, Article.class);
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.updateById(article);
    }

    @Override
    public PageBean<ArticleVO> pageQueryArticle(Integer pageNum, Integer pageSize,
                                                @RequestParam(required = false) Long categoryId,
                                                @RequestParam(required = false) String state) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(categoryId != null, Article::getCategoryId, categoryId);
        queryWrapper.eq(state != null, Article::getState, state);

        Page<Article> page = articleMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
        List<Article> articleList = page.getRecords();
        List<ArticleVO> articleVOList = BeanUtil.copyToList(articleList, ArticleVO.class);
        return new PageBean<>(page.getTotal(), articleVOList);
    }

}
